package nbcp.web.open

import io.swagger.annotations.ApiOperation
import nbcp.base.comm.ApiResult
import nbcp.base.comm.OpenAction
import nbcp.base.comm.StringMap
import nbcp.base.extend.*
import nbcp.base.utils.HttpUtil
import nbcp.comm.JsonpMapping
import nbcp.db.IdCodeName
import nbcp.db.IdName
import nbcp.db.mongo.mor
import nbcp.db.mongo.*
import nbcp.db.mongo.entity.SysUser
import nbcp.db.mongo.entity.UserShareLog
import nbcp.db.redis.rer
import nbcp.service.UploadService
import org.bson.types.ObjectId
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import javax.servlet.http.HttpServletRequest

/**
 * Created by yuxh on 2019/4/8
 */

@OpenAction
@RestController
@RequestMapping("/user")
class WxUserInfo {
    companion object {
        var AppId = "wxf57a49d0f2b44003";
        var AppSecret = "88d3705e7e0e4bd1201ddb96be3cbf20";
    }

    @Autowired
    lateinit var uploadService: UploadService


    //https://developers.weixin.qq.com/miniprogram/dev/api/UserInfo.html
    @ApiOperation("获取 wx OpenId")
    @JsonpMapping("/getOpenId")
    fun getOpenId(
            code: String,
            nickName: String,
            avatarUrl: String,
            gender: Int,
            country: String,
            province: String,
            city: String,
            language: String,
            sharer: String,     //分享者
            shareUrl: String,   //分享的Url
            request: HttpServletRequest): ApiResult<IdCodeName> {

        var ret = ApiResult<IdCodeName>();

        val url = "https://api.weixin.qq.com/sns/jscode2session?appid=${AppId}&secret=${AppSecret}&js_code=${code}&grant_type=authorization_code"

        val ajax = HttpUtil(url);
        val res = ajax.doGet().FromJson<StringMap>();

        ret.msg = res["errmsg"].AsString();
        if (ret.msg.HasValue) {
            return ret;
        }
        var openId = res["openid"] ?: "";

        if (openId.isEmpty()) {
            ret.msg = "获取OpenId失败";
            return ret;
        }


        var user = mor.system.sysUser.query().where { it.wxOpenId match openId }.toEntity();
        //创建用户。
        if (user == null) {
            var user = SysUser()
            user.id = ObjectId().toString();
            user.wxOpenId = openId;
            user.name = nickName;
            if (gender == 1) {
                user.sex = UserSexEnum.Male
            } else if (gender == 2) {
                user.sex = UserSexEnum.Female
            }
            user.location = country + " " + province + " " + city

            user.logo = uploadService.downloadImage(avatarUrl, IdName(), IdName(user.id, nickName));

            mor.system.sysUser.insert(user)
        } else {
            user = mor.system.sysUser.query().where { it.wxOpenId match openId }.toEntity();
        }

        if (sharer.HasValue) {
            var shareLog = UserShareLog();
            shareLog.sharer = IdName(sharer, "")
            shareLog.url = shareUrl;
            shareLog.recver = IdName(openId, "")
            mor.system.userShareLog.insert(shareLog);
        }

        ret.data = IdCodeName(user!!.id, openId, user.name);

        return ret;
    }
}
